package cn.lls.aspect;

import cn.lls.base.exception.LlsException;
import cn.lls.base.result.R;
import cn.lls.base.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;


/**
 * 数据校验的切面，当数据不符合要求时，直接返回错误
 * @ClassName ValidationAspect
 * @Author 划水艺术家
 * @Date 2022/11/16 0:26
 * @Version 1.0
 **/
@Aspect
@Component
@Slf4j
public class ValidationAspect {

    /**
    * 以 controller 为切入点，数据校验
    */
    @Pointcut("execution(public * cn.lls.controller..*.*(..))")
    public void validationPoint(){}

    @Before("validationPoint()")
    public void beforeV(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        for (Object o: args){
            if (o instanceof BindingResult){
                BindingResult o1 = (BindingResult) o;
                if (o1.hasErrors()){
                    for(ObjectError error: o1.getAllErrors()){
                        log.info("validation error: {}", error.getDefaultMessage());
                        throw new LlsException(ResultCode.PARAM_ERROR, error.getDefaultMessage());
                    }
                }
            }
        }
    }
}
